package com.letoken.platform.app.consumer;

import com.alibaba.fastjson.JSONObject;
import com.letoken.platform.app.service.AppUserLampService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.CustomExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RestController;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
@RabbitListener()
@RestController
public class FundReleaseConsumer {
    public final static String exchange = "letoken.FundRelease1";
    public final static String routingKey = "release1.#";
    public final static String queue = "topic.fund.release1";
    @Bean
    public Queue releaseQueue() {
        return new Queue(queue);
    }

    @Bean
    public CustomExchange releaseExchange() {
        Map<String, Object> args = new HashMap<>(1);
        return new CustomExchange(exchange, "topic", true, false, args);
    }

    @Bean
    public Binding releaseBindingNotify(@Qualifier("releaseQueue") Queue queue,
                                        @Qualifier("releaseExchange") CustomExchange customExchange) {
        return BindingBuilder.bind(queue).to(customExchange).with(routingKey).noargs();
    }

    @Autowired
    AppUserLampService appUserLampService;

    @RabbitListener(queues = FundReleaseConsumer.queue)
    @RabbitHandler
    public void fundReleaseConsumer(@Payload String message) {
        log.info("收到降低上级实时业绩消息:{}",message);
        FundReleaseConsumer.FundReleaseDto dto = JSONObject.parseObject(message, FundReleaseConsumer.FundReleaseDto.class);
        try {
            appUserLampService.updateLamd(dto.getUserId(),dto.getAmount());
        }catch (Exception e){
            log.error("降低上级实施业绩失败,消息{},出错信息:{}", message,e.getMessage());
            throw new RuntimeException(e);
        }

    }

    @Data
    public static class FundReleaseDto implements Serializable {
        private Integer userId;
        private BigDecimal amount;
    }
}
